package org.baygo.view.api.listener;

import org.babygo.connect.NettyFileOperator;
import org.baygo.view.api.impl.MyViewOperator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

public class StartButtonActionListener implements ActionListener{
	private Logger log = LoggerFactory.getLogger(StartButtonActionListener.class);

	private static NettyFileOperator fileServer = new NettyFileOperator();
	{
		NettyFileOperator.setViewOperator(MyViewOperator.getMyOperator());
	}
    private JTextArea logArea;
    private JButton startButton;
    private JButton stopButton;

    public static FileServerOperator getFileServer() {
		return fileServer;
	}

	public StartButtonActionListener(){}

    public StartButtonActionListener(JTextArea logArea, JButton startButton, JButton stopButton){
    	this.logArea = logArea;
    	this.startButton = startButton;
    	this.stopButton = stopButton;
    }

	public void actionPerformed(ActionEvent e) {
		SwingWorker <String, Boolean> server = new SwingWorker<String, Boolean>(){

			@Override
			protected String doInBackground() throws Exception {
				publish(fileServer.start((int)(Math.random()*9+1)*1000));
				log.info("启动完毕");
				return "启动完毕";
			}

			@Override
			protected void process(List<Boolean> chunks) {
				log.info("process");
				for (Boolean result : chunks) {
					if (result==true){
						logArea.append("[服务端]启动服务成功!\n");
						startButton.setText("已启动...");
						startButton.setEnabled(false);
						stopButton.setBackground(Color.red);
						stopButton.setEnabled(true);
					}
				}
			}
		};
		server.execute();
	}

}